package cn.zyq.ykb.system.utils.redis.limit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;

@Service
@Slf4j
public class RequestLimitService {

    @Resource(name = "redisScriptForRequestLimit")
    private DefaultRedisScript<Boolean> redisScriptForRequestLimit;
    @Resource(name = "redisTemplateForLua")
    private RedisTemplate<Object, Serializable> redisTemplateForLua;

    /**
     * 限制某个请求在规定时间内访问次数
     *
     * @param key        键
     * @param limit      限制次数
     * @param expireTime 过期时间，单位：毫秒
     * @return true: 表示被限制了
     */
    public Boolean limit(String key, Integer limit, Long expireTime) {
        return this.redisTemplateForLua.execute(this.redisScriptForRequestLimit, Collections.singletonList(key), String.valueOf(limit), String.valueOf(expireTime));
    }

    /**
     * 限制某个请求在规定时间内访问次数
     *
     * @param key        键
     * @param limit      限制次数
     * @param expireTime 过期时间，单位：毫秒
     * @return true: 表示被限制了
     */
    public Boolean limit(String key, Integer limit, Integer expireTime) {
        return this.redisTemplateForLua.execute(this.redisScriptForRequestLimit, Collections.singletonList(key), String.valueOf(limit), String.valueOf(expireTime));
    }
}
